//
//  Three2ViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/12/1.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "Three2ViewController.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
//#define MAXFLOAT  90


#import "Three2DetailViewController.h"


@interface Three2ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;



//获取网络信息的数组
@property(nonatomic,strong) NSMutableArray *list;
//网路请求
@property(nonatomic,strong)AFHTTPSessionManager *manager;


//无订单显示图片view加image以及button
@property(nonatomic,strong) UIView *view20w;
@property(nonatomic,strong) UIButton *btnw;
@property(nonatomic,strong) UIImageView *imageVieww;

@end

@implementation Three2ViewController


static int cur_page = 1;

//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.topView.hidden = YES;
    self.list = [NSMutableArray arrayWithCapacity:0];
    self.tableView.backgroundColor = BACKGROUND1;
    self.view.backgroundColor = BACKGROUND1;

    //进行刷新控制
    [self setupRefresh2];
    
    self.view20w = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];
    
    self.view20w.backgroundColor = BACKGROUND1;
    [self.view addSubview:self.view20w];
    
    
    self.imageVieww = [[UIImageView alloc]initWithFrame:CGRectMake((self.view20w.frame.size.width-60)/2, (self.view20w.frame.size.height-80-70)/2, 60, 80)];
    self.imageVieww.image = [UIImage imageNamed:@"order_null"];
    
    [self.view20w addSubview:self.imageVieww];
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0,(self.view20w.frame.size.height-80-70)/2+self.imageVieww.frame.size.height+10, self.view20w.frame.size.width, 40)];
    lbl.text = @"  还没有新的订单哦~";
    lbl.textColor = [UIColor grayColor];
    lbl.textAlignment  = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:18];
    [self.view20w addSubview:lbl];
    
    self.btnw  = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];
    [self.btnw addTarget:self action:@selector(headerRereshing1) forControlEvents:UIControlEventTouchUpInside];
    [self.view20w addSubview:self.btnw];
    self.view20w.hidden = YES;
    self.tableView.hidden = NO;

    
}



#pragma mark刷新数据
- (void)setupRefresh2
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing1)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing1)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";
    
    
    
    
}


- (void)headerRereshing1
{
    
    //加载数据
    [self sendAPI];
    
    
}


- (void)footerRereshing1
{
    
    [self sendAPI2];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [self.tableView footerEndRefreshing];
    
}


-(void)sendAPI
{
    
    
   
    NSString *urlStr = [NSString stringWithFormat:@"%@order_summary",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken , @"status" : @"12" , @"cur_page" : @"1"};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [self.tableView headerEndRefreshing];
                
                return ;
            }
            else
            {
                NSArray *array = responseObject[@"data"][@"list"];
                
                if (array.count != 0 )
                {
                    [self.list removeAllObjects];
                    self.list = [NSMutableArray arrayWithArray:array];
                    self.view20w.hidden = YES;
                    self.tableView.hidden = NO;
                    
                }
                else
                {
                
                    self.view20w.hidden = NO;
                    self.tableView.hidden = YES;
                
                }
                
                
                
//                NSLog(@"33398098990902111  %@",responseObject);
            }
            
            
            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
            
        }
        else
        {
            [self.tableView headerEndRefreshing];
            self.view20w.hidden = NO;
            self.tableView.hidden = YES;
            
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            //            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
            //
            //                //将所有存储的数据进行清除，并且跳转到登录界面
            //                [self.dataSingleton removeLocalData:@"wTel"];
            //                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
            //                [self presentViewController:login animated:YES completion:nil];
            //
            //            }
            
            
            
            
        }
        

        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.tableView headerEndRefreshing];
        self.view20w.hidden = NO;
        self.tableView.hidden = YES;

        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
        
        
    }];
}


#pragma mark 进行footer的加载数据
-(void)sendAPI2
{
    
    cur_page ++;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@order_summary",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken , @"status" : @"12" , @"cur_page" : [NSString stringWithFormat:@"%d",cur_page]};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [self.tableView footerEndRefreshing];
                
                return ;
            }
            else
            {
                NSArray *array = responseObject[@"data"][@"list"];
                
                
                if (array.count != 0)
                {
                    [self.list removeAllObjects];
                    self.list = [NSMutableArray arrayWithArray:array];
                    
                    
                    
                }
             else
             {
             
             
             
             
             }
                
                
            }
            [self.tableView footerEndRefreshing];
            
            [self.tableView reloadData];
        }
        else
        {
        
            [self.tableView footerEndRefreshing];
            
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
        
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.tableView footerEndRefreshing];
        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
        
        
    }];
    
    
    
    
    
}




-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{


 return    self.list.count;


}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 20;
    
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;

}




-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
//    CGSizeMake(230, MAXFLOAT);
//    
//       NSString *total  = [NSString stringWithFormat:@"%d",[[self.list[section] objectForKey:@"far_num"] intValue] + [[self.list[section] objectForKey:@"near_num"] intValue]];
//    
//    
//        NSString *price = [NSString stringWithFormat:@"%d",[[self.list[section] objectForKey:@"far_price"] intValue] + [[self.list[section] objectForKey:@"near_price"] intValue]];
//    
//   NSString *message =  [NSString stringWithFormat:@"总送货%@家 (远%@家  近%@家) 运费共: %@元",total,[self.list[section] objectForKey:@"far_num"],[self.list[section] objectForKey:@"near_num"],price];
//
//    //自动拉伸自定义的高度
//    CGSize textRealSize = [message boundingRectWithSize:CGSizeMake(230, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
    
    
    return 216 ;
    
    
}





-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    

    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    view1.backgroundColor = [UIColor whiteColor];
   
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 53, ViewWidth, 0.3)];
    view2.backgroundColor = [UIColor lightGrayColor];
    [view1 addSubview:view2];
    
    
    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 53+54, ViewWidth, 0.3)];
    view3.backgroundColor = [UIColor lightGrayColor];
    [view1 addSubview:view3];
    
    
    
    UIView *view4 = [[UIView alloc]initWithFrame:CGRectMake(0, 53+54*2, ViewWidth, 0.3)];
    view4.backgroundColor = [UIColor lightGrayColor];
    [view1 addSubview:view4];

    
    
    UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 54)];
    lbl1.text = @"订单编号";
    lbl1.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl1];
    lbl1.font = [UIFont systemFontOfSize:16];
    
    UILabel *lbla = [[UILabel alloc]initWithFrame:CGRectMake(90, 0, 230, 54)];
    lbla.text = [NSString stringWithFormat:@"%@",[self.list[section] objectForKey:@"order_id"]];
    [view1 addSubview:lbla];
    lbla.font = [UIFont systemFontOfSize:15];
    
    
    UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(15, 53, 100, 54)];
    lbl2.text = @"下单时间";
    lbl2.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl2];
    lbl2.font = [UIFont systemFontOfSize:16];
    
    
    
    int ordertime = [[self.list[section] objectForKey:@"order_time"] intValue];
    NSDate *orderdate = [[NSDate alloc]initWithTimeIntervalSince1970:ordertime];
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    [formatter2 setDateFormat:@"yyy-MM-dd  HH:mm"];

    
    
    UILabel *lblb = [[UILabel alloc]initWithFrame:CGRectMake(90, 53, ViewWidth *0.72, 54)];
    lblb.text = [formatter2 stringFromDate:orderdate];
    [view1 addSubview:lblb];
    lblb.font = [UIFont systemFontOfSize:14];
    
    
    
    
    
    
    UILabel *lbl3 = [[UILabel alloc]initWithFrame:CGRectMake(15, 53 +54, 100, 54)];
    lbl3.text = @"运        费";
    lbl3.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl3];
    lbl3.font = [UIFont systemFontOfSize:16];
    
    
    
    UILabel *lblc = [[UILabel alloc]initWithFrame:CGRectMake(90, 53 + 54, 230, 54)];

    
    
    NSString *total = [NSString stringWithFormat:@"%@",[self.list[section] objectForKey:@"amount_total"]];
  
    
    NSString *price = [NSString stringWithFormat:@"%.1f", [total floatValue] - [[self.list [section] objectForKey:@"product_amount"] floatValue]];
    
    
    
    
    //商家数目
    NSString  *number = [NSString stringWithFormat:@"%d",[[self.list[section] objectForKey:@"near_num"] intValue] + [[self.list[section] objectForKey:@"far_num"] intValue]];
    
    lblc.text = [NSString stringWithFormat:@"总送货%@家(远%@家  近%@家)运费共:%@元",number,[self.list[section] objectForKey:@"far_num"],[self.list[section] objectForKey:@"near_num"],price];
    
    [lblc setNumberOfLines:0];
    CGSize size = CGSizeMake(230, 54);
    CGSize labelMSSize = [lblc.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    [lblc setFrame:CGRectMake(90, 53+54+10, labelMSSize.width , labelMSSize.height)];

    
    
    [view1 addSubview:lblc];
    lblc.font = [UIFont systemFontOfSize:13];
    
    
    
    
    
    UILabel *lbl4 = [[UILabel alloc]initWithFrame:CGRectMake(15, 53 +54*2, 100, 54)];
    lbl4.text = @"总  金  额";
    lbl4.textColor = [UIColor lightGrayColor];
    [view1 addSubview:lbl4];
    lbl4.font = [UIFont systemFontOfSize:16];

    
    
    UILabel *lbld = [[UILabel alloc]initWithFrame:CGRectMake(90, 53 +54*2, 230, 54)];
    lbld.text = [NSString stringWithFormat:@"%@元",[self.list[section] objectForKey:@"amount_total"]];
    [view1 addSubview:lbld];
    lbld.font = [UIFont systemFontOfSize:15];

    
    
    
    
    
    
    
    
    
    
    
    
    
    return view1;


    
    
    
}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell3";
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    

    
    
    
    cell.backgroundColor = TiaoColor;
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[self.list [indexPath.section] objectForKey:@"dealer_name"]];
    cell.textLabel.textColor = [UIColor whiteColor];
    
    
    //添加跳转下一个页面的提示图片
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([self.tableView isHeaderRefreshing]  || [self.tableView isFooterRefreshing])
    {
        return;
    }
    
    
    NSInteger row = [indexPath section];
    NSDictionary *dict = [self.list objectAtIndex:row];
    //    TwoDetailViewController *twoD = [[TwoDetailViewController alloc]initWithNibName:nil bundle:nil];
    //
    //    twoD.dict = dict;
    //    twoD.oID = [dict objectForKey:@"order_id"];
    //    [self.navigationController pushViewController:twoD animated:YES];
    
    
    
    
    
    Three2DetailViewController *detail = [[Three2DetailViewController alloc]initWithNibName:nil bundle:nil];
    
    detail.oID = [dict objectForKey:@"order_id"];
    
    
    [self.navigationController pushViewController:detail animated:YES];
    
    
    
}





@end
